package com.iot.common.utils;

import jakarta.servlet.http.HttpServletRequest;

public class IPUtil {

    public static String getClientIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For"); // 获取代理服务器传递的真实IP
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP"); // 检查代理客户端IP
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP"); // WebLogic代理客户端IP
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr(); // 如果没有代理，则直接获取客户端IP
        }

        // 处理多级代理的情况（X-Forwarded-For可能包含多个IP）
        if (ipAddress != null && ipAddress.contains(",")) {
            String[] ipArray = ipAddress.split(",");
            ipAddress = ipArray[0].trim(); // 取第一个非未知的IP地址
        }

        return ipAddress;
    }
}
